﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Media3D;

namespace FeatureDetection.Inputter {
    class MouseInputter : IInputter{
        private volatile System.Timers.Timer timer;
        private int remain;
        private System.Windows.FrameworkElement target;

        /// <summary>
        /// 初期設定
        /// </summary>
        /// <param name="parameter">System.Window.FrameworkElement parameter[0] カーソルを取得する基準となるWPF要素, int parameter[1] 寿命フレーム(1/30 /ms)</param>
        public MouseInputter(params object[] parameter) {
            target = (System.Windows.FrameworkElement)parameter[0];
            remain = (int)parameter[1];    //parameter回で終了
        }

        public override bool initialize() { return true; }

        public override void startInput(AddPosition addpos, EndFunc endFunc) {
            timer = new System.Timers.Timer(1000.0/remain);
            timer.Elapsed += (sender, e) => {
                //座標取得ロジック
                var cp = Cursor.Position;
                System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() => {
                    var p = target.PointFromScreen(new System.Windows.Point(cp.X, cp.Y));
                    addpos(new Vector3D(p.X,p.Y, 0));
                }));

                //寿命を全うした
                if(--remain <= 0)   endFunc();
            };

            //ここでendFuncを呼んではいけない
            timer.Disposed += (sender, e) => { };
            timer.Start();
        }

        public override void endInput() {
            timer.Stop();
            timer.Dispose();
            timer = null;
        }
    }
}
